using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class BulkImportEmployeesCommandHandler : IRequestHandler<BulkImportEmployeesCommand, int>
	{
		private readonly IBaseRepository<Employee> _repository;

		public BulkImportEmployeesCommandHandler(IBaseRepository<Employee> repository)
		{
			_repository = repository;
		}

		public async Task<int> Handle(BulkImportEmployeesCommand request, CancellationToken cancellationToken)
		{
			var list = new List<Employee>();
			foreach (var dto in request.Employees)
			{
				// 简单去重策略：以用户名或工号存在则跳过
				var exists = await _repository.GetAll()
					.AnyAsync(x => !x.IsDeleted && (x.UserName == dto.UserName || x.WorkNo == dto.WorkNo), cancellationToken);
				if (exists) continue;
				list.Add(new Employee
				{
					EmployeeId = YitIdHelper.NextId(),
					UserName = dto.UserName,
					FullName = dto.FullName,
					WorkNo = dto.WorkNo,
					DepartmentId = dto.DepartmentId,
					Email = dto.Email,
					Gender = dto.Gender,
					Address = dto.Address,
					Phone = dto.Phone,
					IdCardNo = dto.IdCardNo,
					Title = dto.Title,
					Role = dto.Role,
					IsActive = dto.IsActive,
					CreatedAt = DateTime.Now,
					UpdatedAt = DateTime.Now
				});
			}
			if (list.Count == 0) return 0;
			return await _repository.AddRangeAsync(list);
		}
	}
}
